package com.hyg.publish;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created by huangyugen on 2018/07/17
 **/
public class ReceiveLogs1 {

    private static final String EXCHANGE_NAME = "logs" ;
    private static final String HOST = "192.168.1.91";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME,"fanout");
        //如果要在生产者和消费者之间创建一个新的队列，又不想使用原来的队列，临时队列就是为这个场景而生的：
        //
        //首先，每当我们连接到RabbitMQ，我们需要一个新的空队列，
        // 我们可以用一个随机名称来创建，或者说让服务器选择一个随机队列名称给我们。
        //一旦我们断开消费者，队列应该立即被删除。
        //
        //在Java客户端，提供queuedeclare()为我们创建一个非持久化、独立、自动删除的队列名称。
        String queueName = channel.queueDeclare().getQueue();

        //String queue, String exchange, String routingKey
        channel.queueBind(queueName,EXCHANGE_NAME,"");

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println(" [x] Received '" + message + "'");
            }
        };
        channel.basicConsume(queueName, true, consumer);


    }

}
